<template>
  <div class="banner-add">

    <div class="createPost-main-container">
      <el-form ref="form" label-width="120px" :rules="rules" :model="form">
        <el-form-item label="专业">
          <el-select v-model="form.vocationalIdx" filterable placeholder="专业" @change="changeVocational(form.vocationalIdx)">
            <el-option
              v-for="(vocational, index) in vocationals"
              :key="index"
              :label="vocational.name"
              :value="index"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="班级名称" prop="name">
          <el-input v-model="form.name" type="text" maxlength="20" show-word-limit />
        </el-form-item>
        <el-form-item label="学生人数">
          <el-input v-model="form.students" type="number" maxlength="20" show-word-limit />
        </el-form-item>
        <el-form-item label="班级描述">
          <el-input v-model="form.description" type="textarea" maxlength="200" show-word-limit />
        </el-form-item>
      </el-form>
    </div>

    <sticky :class-name="'cms-sub-navbar '+ajaxStatus">
      <el-button :loading="ajaxStatus" style="margin-left: 10px;" type="success" @click="submitForm('up')">
        发布
      </el-button>
      <el-button :loading="ajaxStatus" @click="reset()">
        取消
      </el-button>
    </sticky>
    <input
      :id="'videoIdx' + tabName"
      ref="inputer"
      type="file"
      name="file"
      style="display:none"
      @change="handleFileChange"
      @touchstart="handleFileChange"
    >

  </div>
</template>

<script>
import { getEditData, postData } from '@/api/vocation/classes'
import Sticky from 'components/Sticky'
import { uploadFile } from 'api/common'
import { defaultImg } from 'utils/basic'
import { getVocationalLink } from '@/api/common'

const defaultForm = {
  name: '',
  students: '',
  vocational: {},
  vocationalIdx: 0,
  description: ''
}

export default {
  components: { Sticky },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    },
    tabName: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      ajaxStatus: false,
      form: Object.assign({}, defaultForm),

      uploadVideo: false,
      uploading: false,
      flagIdx: '',
      vocationals: [],
      videoForm: {
        file: null,
        path: 'home'
      },

      rules: {
      }
    }
  },
  computed: {
  },
  created() {
    if (this.isEdit) {
      const id = this.$route.query && this.$route.query.id
      this.fetchData(id)
    }
    this.getLinkList()
  },
  methods: {
    getLinkList() {
      getVocationalLink().then(e => {
        this.vocationals = e.data.content
        this.vocationals.forEach((value, index) => {
          if (this.form.vocational && value.id === this.form.vocational.id) {
            this.form.vocationalIdx = index
          }
        })
      })
    },
    removeBanner(idx) {
      if (this.form.bannerImages.length > 1) {
        this.form.bannerImages.splice(idx, 1)
      }
    },
    successUploadBanner() {
      this.form.bannerImages.push(defaultImg())
    },
    addCard() {
      // const index = this.basicItems.length + 1
      this.form.materials.push({
        name: '',
        content: [
          { value: '' }
        ]
      })
    },
    addBanner() {
      this.form.bannerImages.push(defaultImg())
    },
    deletCard(idx) {
      this.form.materials.splice(idx, 1)
    },
    addItemContent(item) {
      console.log(item)
      item.content.push({
        value: ''
      })
    },
    moveUp(index) {
      if (index < 1) {
        return
      }
      // 重制排序
      const upData = this.basicItems[index - 1]
      this.basicItems.splice(index - 1, 1)
      this.basicItems.splice(index, 0, upData)
    },

    // 下移
    moveDown(index) {
      // 重制排序
      const upData = this.basicItems[index + 1]
      this.basicItems.splice(index + 1, 1)
      this.basicItems.splice(index, 0, upData)
    },

    uploadVideoBtn(idx) {
      this.uploadVideo = true
      this.flagIdx = idx
    },

    deleteContent(idx, index) {
      this.form.materials[idx].content.splice(index, 1)
    },
    changeVocational(idx) {
      this.form.vocational = this.vocationals[idx]
    },

    // 上传文件 图片/视频
    handleFileChange() {
      if (this.uploading) {
        return
      }
      const inputDOM = this.$refs.inputer
      const file = inputDOM.files[0]
      // 判断是否是图片上传
      const imageType = /image.*/
      const isImage = file.type.match(imageType)
      this.checkImg(file, isImage).then(() => {
        this.uploading = true
        const formData = new window.FormData()
        Object.keys(this.videoForm).forEach((y) => {
          formData.append(y, this.videoForm[y])
        })
        formData.append('file', file)
        uploadFile(formData).then((re) => {
          this.uploading = false
          const { data } = re
          this.basicItems[this.flagIdx].value = data
          this.basicItems[this.flagIdx].videoUrl = data
          this.basicItems[this.flagIdx].videoContent = `<div>
                    <video
                      controls
                      x5-playsinline playsinline webkit-playsinline
                      poster="/${this.videoImgData.imgUrl}"
                      class="video_upload_con"
                      object-fit: fill" >
                        <source src="${data}" type="video/mp4" />
  		                  您的浏览器不支持video标签播放视频
                    </video>
                </div>`
          this.uploadVideo = false
          this.$refs.inputer.value = ''
          this.videoImgData.imgUrl = ''
        })
      })
    },

    // 获取上传图片宽高
    checkImg(file) {
      return new Promise((resolve, reject) => {
        if (file.type.includes('video')) {
          const isMP4 = file.type === 'video/mp4'
          if (!isMP4) {
            this.$alert('图片的格式暂时仅支持mp4格式哦～', '提示', {
              confirmButtonText: '确认',
              type: 'warning'
            })
            return
          }
          resolve({
            width: '',
            height: ''
          })
        } else {
          this.$alert('请上传正确格式的文件', '提示', {
            confirmButtonText: '确认',
            type: 'warning'
          })
          reject()
        }
      })
    },

    uploadfile() {
      window.document.getElementById(`videoIdx${this.tabName}`).click()
    },

    // 获取编辑数据
    fetchData(id) {
      getEditData(id).then(re => {
        const { data } = re
        this.form = Object.assign(this.form, data)
      })
    },

    /**
       * 保存、发布接口
       *
       * id：保存为空，编辑传列表id
       */
    submitForm(status) {
      if (this.ajaxStatus) {
        return
      }
      this.ajaxStatus = true

      const errorText = this.validateForm()
      if (errorText) {
        this.ajaxStatus = false
        this.$message.error(errorText)
        return
      }
      this.form.vocational = this.vocationals[this.form.vocationalIdx]
      this.$refs.form.validate(valid => {
        if (valid) {
          this.form.status = status
          postData(this.form)
            .then(re => {
              this.ajaxStatus = false
              this.$notify({
                title: '成功',
                message: '操作成功',
                type: 'success',
                duration: 2000
              })
              this.reset()
            })
            .catch(() => {
              this.ajaxStatus = false
            })
        } else {
          this.ajaxStatus = false
          this.$message.error('请正确填写完整信息后再发布')
          return false
        }
      })
    },

    resetActivityType(idx) {
      this.$set(this.basicItems[idx], 'detailLink', '')
      this.$set(this.basicItems[idx], 'buyLink', [{
        name: '',
        buyPlatformColor: '#000',
        link: ''
      }])
    },

    reset() {
      // 编辑发布后直接关闭tab跳转至列表页面
      if (+this.tabName > 2) {
        this.$emit('removeTab', this.tabName, '1')
        return
      }
      this.form = Object.assign({}, defaultForm)
      this.$refs['form'].resetFields()
      this.$emit('removeTab', this.tabName)
    },

    /**
       * 验证表单项
       * @returns {string} 错误提示
       */
    validateForm() {
      return ''
    }
  }
}
</script>
<style lang="scss">
  .href-remark{
    color: #5e6d82;
    .red {
      background-color: #fdf6ec;
      color: #e6a23c;
    }
  }
  .logo-card{
    margin-bottom: 10px;
  }
  .video_upload_con{
    height: 100px;
    width: auto;
  }
</style>

